package org.aurora.core.biz.service.impl;

import org.aurora.core.biz.persistence.MainSchedulerMapper;
import org.aurora.core.biz.service.IMainSchedulerService;
import org.aurora.core.common.exception.CompeteMainSchedulerException;
import org.aurora.model.entity.MainSchedulerLockInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MainSchedulerServiceImpl implements IMainSchedulerService {

    @Resource
    private MainSchedulerMapper mainSchedulerMapper;

    @Override
    public boolean tryToBeMainScheduler(MainSchedulerLockInfo mainSchedulerLockInfo) {
        return mainSchedulerMapper.update(mainSchedulerLockInfo) >= 1;
    }

    @Override
    public MainSchedulerLockInfo queryMainSchedulerLockInfo() {
        List<MainSchedulerLockInfo> mainSchedulerLockInfoList = mainSchedulerMapper.query();

        if (mainSchedulerLockInfoList != null && mainSchedulerLockInfoList.size() == 1) {
            return mainSchedulerLockInfoList.get(0);
        }

        throw new CompeteMainSchedulerException("main scheduler lock info can only be one");
    }
}
